package com.wang.interview.designmode.iterator;

/**
 * @author: wang
 * @date: 2021/8/2 09:25
 * @description: 以数组的方式存放学生
 */
public class Class1<E> {

    private E[] es;
    private int index;
    private int last;              // last = es.length - 1;  让构造器来初始化值。构造器没有第二句就会导致这个值在类加载的时候就定为-1了
    Itr itr = new Itr();

    public Class1(E[] es) {
        this.es = es;
        last = es.length - 1;
    }

    /**
     * 添加元素
     * @param e
     */
    public void add(E e){
        if (!itr.hasNext()){throw new IndexOutOfBoundsException();}
        this.es[index] = e;
    }

    // 删除元素
    public E remove(int index){
        return itr.remove(index);
    }

    /**
     * 遍历展示元素
     */
    public void show(){
        System.out.println("==============class1===============");
        while (itr.hasNext()){
            E e = itr.next();
            System.out.println(e);
        }
    }


    private class Itr implements MyIterator<E>{

        @Override
        public boolean hasNext() {
            return index <= last;
        }

        // todo：删除元素

        @Override
        public E next() {
            E e = es[index];
            index ++;
            return e;
        }
        @Override
        public E remove(int index) {
            throw new UnsupportedOperationException();
        }
    }

}
